import React, { Component, Fragment } from "react";
// antd
import { Dropdown, Menu, Button, Col, Pagination, Form, Input, Tag, Select, message, Modal, Table, Space, Switch } from "antd";
import { DownOutlined } from '@ant-design/icons';

import ExportJsonExcel from "js-export-excel";
import Action from "@c/buttonAction/Index";
import { pagination_size_option } from "../../../utils/common"

// http
import http from '../../../utils/request';
const { Option } = Select;
const { TextArea } = Input;



class CloudAppkey extends Component {
    constructor(props){
        super(props);
        this.state = {
            // 表格分页
            total: '',
            page: 1,
            page_number: 10,
            dataSource: [],
            columns: [
                {title: "appkey", dataIndex: "appkey", key: "appkey", width: "300px"},
                {title: "评分", dataIndex: "score", key: "score"},
                {title: "告警", dataIndex: "alarm", key: "alarm",
                    render: (text, rowData) => {
                        return (
                            <Switch 
                                size="small"
                                defaultChecked={rowData.alarm} 
                                onClick={() => this.onChangeAlarmStatus(rowData.id)} 
                            />
                        )
                    }
                },
                {title: "云平台", dataIndex: "cloud-platform", key: "cloud-platform",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.platform}-{rowData.account_name}</Tag>                                
                            </div>
                        )
                    }
                },
                {title: "业务标签", dataIndex: "business", key: "business",
                    render: (text, rowData) => {
                        return(
                            <div>
                                <Tag color="green">{rowData.business}</Tag>
                            </div>
                        )
                    }
                },
                {title: "服务状态", dataIndex: "service_status", key: "service_status"},
                {title: "服务名称", dataIndex: "service_name", key: "service_name"},
                {title: "服务类型", dataIndex: "service_type", key: "service_type"},
                {title: "服务应用类型", dataIndex: "service_app_type", key: "service_app_type"},
            ],
            selectedRowKeys: [],
            loading: false,
            search_appkey: '',
            search_account_name: null,
            search_platform: null,
            search_option_account: [],
            search_option_platform: [],
            visable_label: false,
            loading_label: false,
            label_list_option: [],
            label_list_option_name: [],
            label_appkey_list: [],
        }
        this.formRefAdd = React.createRef();
        this.formRefEdit = React.createRef();
        this.formRefMsg = React.createRef();
        this.formRefLabel = React.createRef();
    }

    componentDidMount() {
        this.loadData()
        this.loadDataPlatform()
        this.loadDataBusiness()
    }

    loadDataBusiness = () => {
        const requestDataBusiness = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/business', {params: requestDataBusiness}).then(response=>{
            const resp_data = response.data.data.items
            const label_list_option = []
            const label_list_option_name = []
            for (let i = 0; i < resp_data.length; i++) {
                label_list_option.push(<Option key={resp_data[i].id}>{resp_data[i].name}</Option>)
                label_list_option_name.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)

            }
            this.setState({
                label_list_option: label_list_option,
                label_list_option_name: label_list_option_name
            })
        })
    }

    loadDataPlatform = () => {
        const requestData = {
            'page': 1,
            'limit': 1000,
        }
        http.get('/cloud/platform', {params: requestData}).then(response=>{
            const search_option_platform = []
            const resp_data = response.data.data.items
            for (let i = 0; i < resp_data.length; i++) {
                search_option_platform.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
            }
            this.setState({
                search_option_platform: search_option_platform
            })
        })
    }

    loadData = () => {
        this.setState({
            loading: true
        })
        const requestData = {
            'page': this.state.page,
            'limit': this.state.page_number,
            'appkey__contains': this.state.search_appkey,
            'platform': this.state.search_platform,
            'account_name': this.state.search_account_name,
        }

        // 获取分组列表
        http.get('/cloud/appkey', {params: requestData}).then(response=>{
            this.setState({
                dataSource: response.data.data.items,
                total: response.data.data.pages.total,
                loading: false
            })
        }).catch()
    }

    /** 切换每页数量 */
    onChangeSizePage = (page, page_number) => {
        this.setState({
            page: page,
            page_number: page_number,
        }, () => {
            this.loadData()
        })
    }

    /** 云平台搜索 */
    onFinishSearch = (data) => {
        this.setState({
            page: 1,
            search_appkey: data.appkey ? data.appkey : null,
            search_account_name: data.account_name ? data.account_name : null,
            search_platform: data.platform ? data.platform : null,
        })
        this.loadData()
    }

    // 搜索切换云平台
    onChangePlatform = (value) => {
        if (value) {
            this.setState({
                search_instance_platform: value
            })

            const requestData = {
                'page': 1,
                'limit': 1000,
                'platform': value
            }
    
            http.get('/cloud/account', {params: requestData}).then(response=>{
                const search_option_account = []
                const resp_data = response.data.data.items
                for (let i = 0; i < resp_data.length; i++) {
                    search_option_account.push(<Option key={resp_data[i].name}>{resp_data[i].name}</Option>)
                }
                this.setState({
                    search_option_account: search_option_account
                })
            })

        } else {
            this.setState({
                search_option_account: '',
            })
        }
    }

    // 搜索云账户
    onChangeAccountName = (value) => {
        this.setState({
            search_account_name: value ? value : null
        })
    }

    // 批量选中标签
    onSelectChange = (selectedRowKeys) => {
        console.log('selectedRowKeys: ', selectedRowKeys)
        this.setState({
            selectedRowKeys: selectedRowKeys
        })
    }

    // 批量打标签任务取消
    onFinishLabelCancel = () => {
        this.formRefLabel.current.resetFields()
        this.setState({
            visable_label: false,
            selectedRowKeys: [],
        })
    }

    // 批量打标签任务提交
    onFinishLabel = (data) => {
        this.formRefLabel.current.resetFields()
        this.setState({
            loading_label: true
        })
        const requestData = {
            business_id: data.business_id,
            label_appkey_list: data.label_appkey_list,
            operation_type: 'change_label',
        }
        http.patch('/cloud/appkey', {params: requestData}).then(response=>{
            message.success(response.data.msg)
            this.setState({
                loading_label: false,
                visable_label: false,
                selectedRowKeys: [],
            })
            this.loadData()
        })
    }

    // 批量打标签按钮
    onLabelBtn = () => {
        if (this.state.selectedRowKeys.length>0) {

            // 获取主机列表
            const requestData = {
                instance_id_list: this.state.selectedRowKeys,
                operation_type: 'get_appkey_list',
            }
            console.log('requestData: ', requestData)
            http.patch('/cloud/appkey', {params: requestData}).then(response=>{
                const resp_data = response.data.data
                const resp_data_2 = resp_data.join("\n")
                this.setState({
                    label_appkey_list: resp_data_2
                })

                this.formRefLabel.current.setFieldsValue({
                    label_appkey_list:  resp_data_2
                })
            }).catch()

            this.setState({
                visable_label: true,
            })
        } else {
            message.info('请先选中需要打标签的资源实例')
        }
    }

    // 修改资源巡检状态
    onChangeAlarmStatus = (id) => {
        this.setState({
            loading: true
        })
        const requestData = {
            id: id,
            operation_type: 'change_alarm_status',
        }
        http.patch('/cloud/appkey/' + id, requestData).then(response=>{
            message.success(response.data.msg)
            this.setState({
                loading: false
            })
            this.loadData()
        }).catch()
    }

    // 一键导出
    onexportExcelBtn = () => {
        // 不同云产品添加自定义字段
        const _cmdb_sheet_filter = ["appkey", "platform", "account_name", "business", "service_status", "service_name", "service_type", "service_app_type"]
        const _cmdb_sheet_header = ['APPKEY', '云平台', '云账户', '业务线', '服务状态', '服务名称', '服务类型', '服务应用类型']

        let option = {}
        option.fileName = "商家后台Appkey列表"
        option.datas = [
            {
                sheetData: this.state.dataSource,
                sheetName: "商家后台Appkey列表",
                sheetFilter: _cmdb_sheet_filter,
                sheetHeader: _cmdb_sheet_header
            }
        ]
        var toExcel = new ExportJsonExcel(option)
        toExcel.saveExcel()
    }

    render(){
        const { loading, dataSource, columns, page, total, search_option_platform, search_option_account, visable_label, selectedRowKeys, label_list_option,
            loading_label
        } = this.state
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        }

        const operations = (
            <Menu
                items={[
                    {
                        label: (
                            <Action.Button onClick={() => this.onLabelBtn()}>业务线标签</Action.Button>
                        ),
                        key: '0',
                    },
                    {
                        label: (
                            <Action.Button onClick={() => this.onexportExcelBtn()} >导出页面数据</Action.Button>
                        ),
                        key: '1',
                    },
                ]}
            />
        );
        var myStyle = {margin: '20px'}
        var myStyle1 = {margin: '10px', float: 'right'}

        return (
            <Fragment>

                {/* <div style={myStyle1}><Button type="primary" onClick={() => this.onLabelBtn()} >批量打标签</Button></div> */}

                <Form layout="inline" onFinish={this.onFinishSearch}>
                    <Form.Item label="云平台" name="platform">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择区域"
                            optionFilterProp="children"
                            onChange={this.onChangePlatform}
                            filterOption={(input, option) =>
                            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {search_option_platform}
                        </Select>
                    </Form.Item>

                    <Form.Item label="云账户" name="account_name">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 180 }}
                            placeholder="请选择云账户"
                            onChange={this.onChangeAccountName}
                            >
                            {search_option_account}
                        </Select>                      
                    </Form.Item>

                    <Form.Item label="appkey" name="appkey">
                        <Input placeholder="请输入Appkey"  />
                    </Form.Item>
                    <Form.Item shouldUpdate={true}>
                        <Button type="primary" htmlType="submit">搜索</Button>
                    </Form.Item>
                </Form>

                <div style={myStyle1}>
                    <Dropdown overlay={operations}>
                        <Action.Button>
                            <Space>
                                更多操作
                                <DownOutlined />
                            </Space>
                        </Action.Button>
                    </Dropdown>
                </div>

                <Modal
                    title="批量打标签"
                    visible={visable_label}
                    onCancel={this.onFinishLabelCancel}
                    okText="确认"
                    cancelText="取消"
                    footer={null}
                    width="800px"
                >
                    <Form
                        onFinish={this.onFinishLabel}
                        ref={this.formRefLabel}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 14 }}
                    >

                        <Form.Item label="主机列表" name="label_appkey_list">
                            <TextArea disabled autoSize={true}></TextArea>
                        </Form.Item>

                        <Form.Item label="业务列表" name="business_id">
                        <Select
                            allowClear
                            showSearch
                            style={{ width: 200 }}
                            placeholder="请选择业务线"
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            {label_list_option}
                        </Select>
                    </Form.Item>

                        <Form.Item>
                            <Button loading={loading_label} htmlType="submit" type="primary">确定</Button>
                        </Form.Item>                                                               
                    </Form>           
                </Modal>
                
                <div style={myStyle1}></div>
                <div>
                    <Table
                        pagination={false} 
                        rowSelection={rowSelection} 
                        rowKey="id" 
                        columns={columns} 
                        dataSource={dataSource}
                        loading={loading}
                        scroll={{ y: 500, x: '70vw' }}
                    >
                    </Table>
                </div>

                <div style={myStyle}>
                    <Col span={16}>
                        <Pagination
                            onChange={this.onChangeSizePage}
                            current={page}
                            total={total}
                            pageSizeOptions={pagination_size_option}
                            showSizeChanger
                            showQuickJumper
                            showTotal={total => `Total ${total} items`}
                        />
                    </Col>
                </div>

            </Fragment>
        )
    }
}
export default CloudAppkey;